import util from "../util";
import instance from "../../service2/scenario/instance";
export default class parentInstanceCollection {
  constructor(clz, api) {
    this.util = util;
    this.info = [];
    this.infoTree = [];
    this.infoCascader = [];
    this.list = [];
    this.listTree = [];
    this.listCascader = [];
    this.records = [];
    this.recordsTree = [];
    this.recordsCascader = [];
    this.api = api;
    this.clz = clz;
    this.valueRecords = [];
  }

  getHierPoint(item,model) {
    let point = {};
    let tem = +new Date();
    point["id"] = tem + item.className + String(item.id);
    point["parentId"] = "root";
    point["model"] = model;
    point["name"] = tem + item.className + item.id;
    point["title"] = tem + item.className + item.id;
    point["pointer"] = {
      id: String(item.id),
      type: item.type,
      className: item.className,
    };
    point["values"] = item.values;
    return point;
  }  
  bulidFilter(filterMap, sign = "like") {
    let arr = [];
    if (!!filterMap) {
      Object.keys(filterMap).map((key) => {
        let curItem = filterMap[key];
        let type = typeof curItem;
        let strWrap = type === "number" || type === "boolean" ? "" : "'";

        if (curItem !== "" && curItem !== undefined && curItem !== null) {
          if (
            sign === "like" &&
            strWrap &&
            key != "className" &&
            key != "type" &&
            key != "id"
          ) {
            arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`);
          } else {
            arr.push(`${key} ${"=="} ${strWrap}${curItem}${strWrap}`);
          }
        }
      });
    }
    return arr.join(" && ");
  }
  setFilteStr(filter, like = true) {
    if (!!filter && filter.constructor === Object) {
      for (let key in filter) {
        (filter[key] === "" || filter[key] === null) && delete filter[key];
      }
    } //删除查询项中属性值为空的查询条件
    filter = this.bulidFilter(filter, like ? "like" : "=");
    return filter;
  }
  setValueRecords() {
    this.valueRecords = this.records.map((d) => {
      if (d.values) {
        return {
          ...d.values,
          ...d,
        };
      }
    });
    return this.valueRecords;
  }
  /***
   * 新增
   * @param records
   * @returns {Promise<boolean|*>}
   */
  async batchAdd(records) {
    let result = await this.api
      .batchAdd(records)
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /***
   * 批量更新
   * @param records
   * @returns {Promise<boolean|*>}
   */
  async batchUpdate(records) {
    let result = await this.api
      .batchUpdate(records)
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 批量删除
   * */
  async delete(filter, like = false) {
    let filterStr = filter;
    if (filter.constructor === Object) {
      filterStr = this.setFilteStr(filter, like);
    }
    let result = await this.api
      .delete({ condition: filterStr })
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteByIds(ids) {
    let result = await this.api
      .deleteByIds(ids)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async queryByIds(ids) {
    let result = await this.api
      .queryByIds(ids)
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 条件查询，当前版本，不分页
   * */
  async query(filter, like = false) {
    let filterStr = filter;
    if (filter.constructor === Object) {
      filterStr = this.setFilteStr(filter, like);
    }
    let result = await this.api
      .query({ condition: filterStr })
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          this.recordsTree = util.getTree(data, "type", "className");
          this.recordsCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 条件查询，当前版本，分页
   * */
  async queryByPage(pageNumber, pageSize, filter, orderBy = {}, like = false) {
    let filterStr = filter;
    if (filter.constructor === Object) {
      filterStr = this.setFilteStr(filter, like);
    }
    let result = await this.api
      .queryByPage(
        pageNumber,
        pageSize,
        { condition: filterStr },
        { orderBy: orderBy }
      )
      .then((data) => {
        if (!!data) {
          this.records = data.records;
          this.total = data.recordCount;
          this.setValueRecords();
          this.recordsTree = util.getTree(data.records, "type", "className");
          this.recordsCascader = util.getCascader(
            data.records,
            "type",
            "className"
          );
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /********************************************************************************************
   * 摘要查询
   * ******************************************************************************************/
  /**
   * 摘要查询，当前版本，不分页
   * */
  async listAllInfo() {
    let result = await this.api
      .queryInfo({})
      .then((data) => {
        if (!!data) {
          this.info = data;
          this.infoTree = util.getTree(data, "type", "className");
          this.infoCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 摘要查询，当前版本，分页
   * */
  async queryInfoByPage(pageNumber, pageSize, filter) {
    let result = await this.api
      .queryInfoByPage(pageNumber, pageSize, { condition: filter })
      .then((data) => {
        if (!!data) {
          this.records = data.records;
          this.total = data.recordCount;
          this.recordsTree = util.getTree(data.records, "type", "className");
          this.recordsCascader = util.getCascader(
            data.records,
            "type",
            "className"
          );
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }

  /********************************************************************************************
   * 版本管理
   * ******************************************************************************************/
  /**
   * 摘要查询，所有版本，不分页
   * */
  async listAllVersionInfo() {
    let result = await this.api
      .queryInfoIncludeUnpublished({})
      .then((data) => {
        if (!!data) {
          this.info = data;
          this.infoTree = util.getTree(data, "type", "className");
          this.infoCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 全部查询，所有版本，分页
   * */
  async listAllVersion() {
    let result = await this.api
      .queryIncludeUnpublished({})
      .then((data) => {
        if (!!data) {
          this.list = data;
          this.listTree = util.getTree(data, "type", "className");
          this.listCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }

  /**
   * 通过其他模型的hier中ids中filter records
   */
  filterRecordsByHierIds(ids) {
    if (!this.records || this.records.length === 0) {
      return [];
    }
    let filterRecords = [];
    filterRecords = this.records.filter((item) =>
      ids.includes(String(item.id))
    );
    return filterRecords;
  }

  /**
   * 全局实例踪合操作，（事务性处理）
   * 结构：[{action:"",model:"",data:[{}],...}]
   * 其中model包括：entity/logic/bi/twins/process/routing/template/statistics 对应的实例
   * */
  async run(data) {
    let result = await util.api.Instance.run(data)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
}
